/**
 * @author bigpizza Slaute
 */
function eventBinding(){
    $("#toggle").click(clickOpt);
    
    bindFormSubmit();
}

function dataBinding(){
    $("#searchtoggle").attr("src", "image/optnone.png");
    
    bindWelcome();
    
    bindFilters();
    
}

function bindWelcome(){
    $("#fragment-1").load("data/welmsg.clip").fadeIn("normal");
}

function bindFilters(){
    $.getJSON("data/filters.json", function(data){
        $.each(data.filters, function(i, item){
            $("<span style='color:#CE9200;font-weight:bold'>" + item.company + "</span>").appendTo("#option");
            $("#option").append("<br>");
            
            $.each(item.platform, function(j, platform){
                $("<input type = checkbox>").attr("id", platform.name).appendTo("#option");
                $("#option").append(platform.name);
                $("#option").append("<br>");
            })
        });
    });
}

function bindFormSubmit(){
    var searchFormOpt = {
        url: "query.do",
        type: "POST",
        dataType: "json",
        beforeSubmit: prepareReq,
        success: showResponse//showResponse()内的参数
    };
    $("#queryForm").ajaxForm(searchFormOpt);
}

function prepareReq(formData, jqForm, searchFormOpt){
    $("#load").css("display", "block");
    $("#results").html("");
    $("#tools").html("");
    var platformList = "";
    // Get all 'checked' platforms
    
    $("#option input:checked").each(function(){
        platformList += this.id + ",";
    });
    
    if (platformList.length < 1) {
        platformList = "U95,";
    }
    // Fill formData to submit
    formData[formData.length - 1].value = platformList.substring(0, platformList.length - 1);
}

function showResponse(response){
    $("#load").css("display", "none");
    $("#results").empty();
	
    if (response.counter == undefined) {
        $("#results").append("Can't Find Any Results.");
    }
    else 
        if (response.counter.length == undefined) {
            $("<input type=checkbox checked>").attr({
                id: response.counter.geneName
            }).appendTo("#results");
            $("#results").append(response.counter.geneName + " (" + response.counter.matchCount +
            ")");
            $("#results").append("<br>");
        }
        else {
            $.each(response.counter, function(i, item){
                $("<input type=checkbox checked>").attr({
                    id: item.geneName
                }).appendTo("#results");
                $("#results").append(item.geneName + " (" + item.matchCount + ")");
                $("#results").append("<br>");
            });
        }
    genToolBtn();
    //add tab "Chart"
    if ($("#Chart").length != 0) {
        $("#Chart").empty();
        $("<img>").attr({
            id: "pic",
            src: response.picInfo.URL,
        }).appendTo("#Chart");
    }
    else {
        addTab('Chart');
        //Show image ;
        $("<img>").attr({
            id: "pic",
            src: response.picInfo.URL,
        }).appendTo("#Chart");
    }
    //add tab "Data Table"
    
	if ($("#DataTable").length != 0) {
		//$("#DataTable").empty();
        $("#DataTable").html("<div class='tabLoading'><img src='image/loading.gif'></div>")
    }
    else {
        addTab('DataTable');
        $("#DataTable").html("<div class='tabLoading'><img src='image/loading.gif'></div>");
    }
    var dataTable;
    dataTable = "<table id='dataTable' class='stripe_tb' width=50% border='0' cellspacing='0' cellpadding='0'><tr><th>Gene Name</th><th>Value</th><th>Probe ID</th><th>Cell Line</th><th>Tissue</th></tr>";
    $.each(response.preRun, function(i, item){
        dataTable = dataTable + "<tr><td>" + item.geneName + "</td>" + "<td>" + item.value +
        "</td>" +
        "<td>" +
        item.probeId +
        "</td>" +
        "<td>" +
        item.cellLine +
        "</td>" +
        "<td>" +
        item.tissue +
        "</td></tr>";
    });
    
    dataTable = dataTable + "</table>";
    //("#DataTable").empty();
    $("#DataTable").html(dataTable);
    bindTable();
}

function genToolBtn(){
    $("#tools").empty();
    // KEGG
    $("<input type=button class='toolBtn'>").attr({
        value: "KEGG...",
        id: "keggButton"
    }).appendTo("#tools");
    $("<div id='pathways'></div>").appendTo("#tools");
    $("#keggButton").click(function(){
        req = checkSelect();
        $("#pathways").html("<div id='pathwayLoading'><center><img src='image/loading.gif'></center></div>")
        $.post("pathway.do", req, function(result){
            var jsonResult = eval('(' + result + ')');
            //清空 div pathways
            $("#pathways").empty();
            //			console.log(result);
            if (jsonResult.pathways == undefined) {
                $("#pathways").append("Can't Find Any PathWay");
            }
            else {
                if (jsonResult.pathways.length == undefined) {
                    $("<li class='pathlinks'>").append($("<a>" + jsonResult.pathways.pathname + "</a>").attr("href", "javascript:sendKEGGReq('" + jsonResult.pathways.pathway + "','" + jsonResult.KEGGIDs + "');")).append("</li>").appendTo("#pathways");
                }
                else {
                    $.each(jsonResult.pathways, function(i, item){
                        $("<li class='pathlinks'>").append($("<a>" + item.pathname + "</a>").attr("href", "javascript:sendKEGGReq('" + item.pathway + "','" + jsonResult.KEGGIDs + "');")).append("</li>").appendTo("#pathways");
                    });
                }
            }
            
        })
    });
    //David
    $("<input type=button class='toolBtn'>").attr({
        value: "David...",
        id: "davidButton"
    }).appendTo("#tools");
    $("#davidButton").click(function(){
        req = checkSelect();
        if ($("#David").length != 0) {
            $("#David").empty();
        }
        else {
            addTab('David');
        }
        
        $("#David").html("<div class='tabLoading'><img src='image/loading.gif'></div>");
        $.post("david.do", req, function(result){
            var davidTable;
            davidTable = "<table id='davidTable' class='stripe_tb' width=50% border='0' cellspacing='0' cellpadding='0'><tr><th>Name</th><th>Value</th></tr>";
            var jResult = eval('(' + result + ')');
            $.each(jResult.result, function(i, item){
                davidTable = davidTable + "<tr><td>" + item.name + "</td>" + "<td>" + item.value + "</td></tr>";
            });
            davidTable = davidTable + "</table>";
            $("#David").empty();
            $("#David").append(davidTable);
            bindTable();
        });
    });
}

function checkSelect(){
    var idList = "";
    // Get All checked gene ids
    $("#results input:checked").each(function(){
        idList += this.id + ",";
    });
    idList = idList.substring(0, idList.length - 1);
    return idList;
}

function sendKEGGReq(item, ids){
    req = item + "," + ids;
    if ($("#" + item).length != 0) {
    }
    else {
        addTab(item);
    }
    $("#" + item).html("<div class='tabLoading'><img src='image/loading.gif'></div>")
    $.post("kegg.do", req, function(result){
        $("#" + item).empty();
        $("#" + item).append(result);
        openInNewWindow();
    });
}

function openInNewWindow(){
    $("area").attr("target", "_blank");
}

//$('#container-1 > ul').tabsClick(2); 触发
